import json
import sys
import os
import logging
import datetime
import Core.MySQLDB as MySQLDB
import Core.Gadget as Gadget


def CreateFolder(fullPathname):
    existed = os.path.exists(fullPathname)
    if not existed:
        os.makedirs(fullPathname)
        print("Create Folder: " + fullPathname)
    else:
        #print("Folder Existed: " + fullPathname)
        pass


cfgPathFilename = os.getcwd() + "\config_simulation.json"
print("Init Config with " + cfgPathFilename)
configFile = json.load(open(cfgPathFilename, 'r', encoding='utf-8'))


# ---connect redis---

# ---connect mq---

# ---connect ES---

class Config(object):

    __initialized = False
    cfg = None
    __loggers__ = {}
    __database = None
    __realtimeViews = {}
    testnum = 0


    def __init__(self, cfg_file=""):
        if not Config.__initialized:
            if cfg_file == "":
                cfg_file = os.getcwd() + "\..\config.json"
            print("Init Config with " + cfg_file)
            Config.cfg = json.load(open(cfg_file, 'r', encoding='utf-8'))
            Config.__initialized = True


    def Logger(self, loggerName, consoleOutput=True):
        #
        if loggerName not in Config.__loggers__:
            #
            logger = logging.getLogger(loggerName)
            logger.setLevel(logging.INFO)  # Log等级总开关

            # ---File Name---
            logDir = Config.cfg["LogDir"]
            folder = logDir + "\\" + loggerName
            Gadget.CreateFolder(folder)

            # fh = logging.FileHandler(folder + "\\" + loggerName , mode='a')
            fh = logging.handlers.TimedRotatingFileHandler(folder + "\\" + loggerName, when='D', interval=1, encoding="utf-8")

            # 指定logger输出格式
            formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s: %(message)s')
            fh.setFormatter(formatter)
            logger.addHandler(fh)

            # 往屏幕上输出
            if consoleOutput:
                sh = logging.StreamHandler()  # 往屏幕上输出
                sh.setFormatter(formatter)  # 设置屏幕上显示的格式
                logger.addHandler(sh)

            #
            Config.__loggers__[loggerName] = logger

        return Config.__loggers__[loggerName]


    def DataBase(self):
        #
        if Config.__database == None:
            print("Create Database Connection")
            # mongoDBAddr = Config.cfg["MongoDBAddress"]
            # mongoDBPort = str(Config.cfg["MongoDBPort"])
            # Config.__database = MongoDB.MongoDB(mongoDBAddr, mongoDBPort, Config.cfg["MongoDBUsername"], Config.cfg["MongoDBPassword"])

            # ---connect database---
            addressPort = configFile["MySQLDBAddressPort"].split(":")
            Config.__database = MySQLDB.MySQLDB(addressPort[0], addressPort[1],
                                username=configFile["MySQLDBUsername"], password=configFile["MySQLDBPassword"])

        return Config.__database


    def RealTime(self, db=0):
        #
        if db not in Config.__realtimeViews:
            print("Create RealTimeView Connection")
            redisAddr = Config.cfg["RedisAddress"]
            redisPort = str(Config.cfg["RedisPort"])
            Config.__realtimeViews[db] = RealTimeView.RealTimeView(address=redisAddr, port=redisPort, db=db)
        return Config.__realtimeViews[db]


# ---Instanced Here---
# config = Config()




